/**
 \* Created with IntelliJ IDEA.
 \* User: 彭诗杰
 \* Date: 2018/7/31 14:58
 \* Description:  服务区state
 \*/
import constants from '../../common/constants'
import util from '../../common/util'
import API from "../../api/api_station";

const state = {
  // 当前服务区
  area: {
    "code": "jingzhu16888xiaogan16888",
    "name": "京珠孝感服务区",
    "lon": 114.07,
    "lat": 31.01,
    "pollutionType": "水环境污染源",
    "province": "湖北",
    "city": "孝感",
    "county": "孝南区",
    "state": true,
    "faulty": true,
    "sewageId": "jingzhu16888xiaogan16888",
    "airId": null,
    "noiseId": null,
    "solidId": null,
    "type": "monitoring",
    "airRelation": null,
    "noiseRelation": null,
    "sewageRelation": null,
    "solidRelation": null
  },
  pagination: {
    page: 1,
    limit: 10,
    total: 100,
  },
  // 有水质监控等服务区
  areaList: [],
  // 无水质监控服务区
  areasNoMonitoring: [],

  // searchBar组件中的服务区树形搜索控件
  areaTreeList: [],

  curAreaName: ''
};

const getters = {
  area: state => {
    return state.area;
  },
  areaList: state => {
    return state.areaList
  },
  areasNoMonitoring: state => {
    return state.areasNoMonitoring;
  },
  areaName: state => {
    return state.curAreaName;
  }
};

const actions = {

  /**
   * 从服务器获取服务区列表数据并填充state中的List
   *
   * @param commit
   * @param state
   * @param context 组件上下文环境
   * @returns {Promise<any>}
   */
  initAreaListAndTreeAct({commit, state}) {
    return new Promise((resolve, reject) => {
      API.getAreas(null).then(backAreas => {
        let areas = areasFormat(backAreas);
        // let treeAreas = transAreaListToTree(areas);

        /**
         * 伪造数据，需要删除
         */
        API.getAreas({type: 'no_monitoring'}).then(noMoAreas => {
          let fNoMoAreas = areasFormat(noMoAreas);
          fNoMoAreas.forEach(noMoArea => areas.push(noMoArea));
          // areas.push.apply(areas, fNoMoAreas);
          commit('setAreaList', areas);
          // commit('addATreeList', treeAreas);
          // 设置当前area
          commit('setArea', areas[0]);
          resolve(areas)
        }).catch(error => {
          reject(error)
        });
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    });
  },

  /**
   * 调用初始化无监测以及有监测服务区并构建搜索树
   * @param commit
   * @param state
   */
  initAndAssembleTreeAct({commit, state}) {
    return new Promise(async (resolve, reject) => {
      let treeAreas = [];
      let areas = [];
      try {
        areas = await API.getAreas(null);
        commit('setAreaList', areas);
        let areasNo = await API.getAreas({type: 'no_monitoring'});
        commit('setAreasNoMonitoring', areasNo);
        let concat = areasFormat(areas.concat(areasNo));
        treeAreas = transAreaListToTree(concat);
      } catch (e) {
        reject(e)
      }
      commit('setATreeList', treeAreas);
      resolve(areas)
    })
  },

  /**
   * 从服务器获取无监测服务区列表并填充state中的areasNoMonitoring
   * @param commit
   * @param state
   */
  initNoMonitoringAreas({commit, state}) {
    return new Promise((resolve, reject) => {
      let params = {
        type: 'no_monitoring'
      };
      API.getAreas(params).then(backAreas => {
        commit('setAreasNoMonitoring', backAreas);
        let areas = areasFormat(backAreas);

        resolve(areas);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  setAreaList({commit, state}, areas) {
    commit('setAreaList', areas);
  },
  setATreeList({commit, state}, areas) {
    commit('setATreeList', areas);
  },
  setCurrentArea({commit, state}, area) {
    commit('setArea', area)
  },
  setCurrentAreaName({commit, state}, areaName) {
    commit('setAreaName', areaName)
  }
};

function areasFormat(backendAreas) {
  let areas = [];
  if (backendAreas) {
    backendAreas.forEach(backArea => {
      let area = {};
      area = util.copyObject(backArea);
      area.district = {};
      area.district.province = backArea.province;
      area.district.city = backArea.city;
      area.district.county = backArea.county;
      areas.push(area)
    })
  }
  return areas;
}

/**
 * 将服务区List转化为Tree组件中可用格式
 * @param areas
 * @returns {*}
 */
function transAreaListToTree(areas) {
  let aTreeData = constants.cities.map(function (city) {
    let label = city.name;
    let id = city.name;
    let children = city.counties.map(function (county) {
      let label = county;
      let id = county;
      let children = [];
      for (let area of areas) {
        if (area.district.city === city.name && area.district.county.indexOf(county) !== -1) {
          children.push({id: area.name + county + city.name, label: area.name});
        }
      }
      if (children) {
        for (let index = 0; index < children.length; index++) {
          if (children[index] && !children[index].id) {
            children.splice(index, 1);
          }
        }
        return {id: id + city.name, label: label, children: children};
      }
    });
    if (children) {
      return {id: id, label: label, children: children}
    }
  });
  return aTreeData;
}

const mutations = {
  setAreaList(state, list) {
    state.areaList = list
  },
  setAreasNoMonitoring(state, list) {
    state.areasNoMonitoring = list;
  },
  setATreeList(state, entity) {
    state.areaTreeList = entity;
  },
  addATreeList(state, entities) {
    for (let entity of entities) {
      state.areaTreeList.push(entity)
    }
  },
  setArea(state, entity) {
    state.area = entity;
  },
  //ymhui,修改服务区名称
  setAreaName(state, entity) {
    state.curAreaName = entity;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
}
